package com.ruoyi.warning.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.warning.domain.entity.*;
import com.ruoyi.warning.mapper.WirelessSensorsMapper;
import com.ruoyi.warning.service.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chenhc
 * @since 2025-06-13
 */
@Service
public class WirelessSensorsServiceImpl extends ServiceImpl<WirelessSensorsMapper, WirelessSensors> implements IWirelessSensorsService {
@Resource
private WirelessSensorsMapper wirelessSensorsMapper;
    @Resource
    private IDevicesService deviceService;
    @Resource
    private IAccessPointsService accessPointsService;
    @Resource
    private IWirelessSensorsManualService wirelessSensorsManualService;
    @Resource
    private IWirelessoidsService wirelessoidsService;

    @Override
    public void addACAPRuijie(Integer id) {
        List<Wirelessoids> wlist = wirelessoidsService.list(new QueryWrapper<Wirelessoids>().lambda()
                .eq(Wirelessoids::getDeviceId,id));
        Map<String, String> resultMap = new HashMap<>();
        if (wlist != null) {
            for (Wirelessoids wirelessoids : wlist) {
                if (wirelessoids.getField() != null && wirelessoids.getOid() != null) {
                    // 将 field 作为键，oid 作为值存入 Map
                    resultMap.put(wirelessoids.getField(), wirelessoids.getOid());
                }
//                else {
//                    throw new ServiceException("部分Oid为空，请保存或检查！");
//                }
            }
        }
        //加ac
        Device device = deviceService.getById(id);
//        if(!"ruijie".equals(device.getOs())){
//            throw new ServiceException("目前设备为"+device.getOs()+",只支持锐捷设备");
//        }
        WirelessSensorsManual wirelessSensors = new WirelessSensorsManual();
        wirelessSensors.setSensorClass("ap-count");
        wirelessSensors.setDeviceId(id);
        wirelessSensors.setSensorType("ciscowlc");
        wirelessSensors.setSensorIndex("0");
        wirelessSensors.setSensorDescr("Connected APs");
        wirelessSensors.setSensorDivisor(1);
        wirelessSensors.setSensorMultiplier(1);
        wirelessSensors.setSensorAggregator("sum");
        String sensorCurrent = getCmdString(resultMap.get("ruijieCurrentUserNum"),device);
        wirelessSensors.setSensorCurrent(ObjectUtils.isNotEmpty(sensorCurrent)?Integer.valueOf(sensorCurrent):null);
        wirelessSensorsManualService.remove(new QueryWrapper<WirelessSensorsManual>().lambda()
                .eq(WirelessSensorsManual::getDeviceId,id)
                .eq(WirelessSensorsManual::getSensorClass,"ap-count"));
        wirelessSensorsManualService.save(wirelessSensors);

        //加ap,所有的都用map来
        List<AccessPoints> list = new ArrayList<>();
        Map<String,String> nameMap = getCmdMap(resultMap.get("ruijieApGeneralApName"),device);
        Map<String,String> ipMap = getCmdMap(resultMap.get("ruijieApGeneralIp"),device);
        List<String> oidList = ipMap.keySet().stream().collect(Collectors.toList());
        Map<String,String> macMap = getCmdMap(resultMap.get("ruijieApGeneralMacAddrColon"),device);
        Map<String,String> statusMap = getCmdMap(resultMap.get("ruijieApGeneralState"),device);
        Map<String,String> apStaMap = getCmdMap(resultMap.get("ruijieApGeneralApStaNum"),device);
        //查看是2.4（1）还是5（2）todo 前端要处理
        Map<String,String> hzMap = getCmdMapHZ(resultMap.get("ruijieApRadioType"),device);
        Map<String,String> apTypeMap = getCmdMap(resultMap.get("ruijieApPID"),device);
        Map<String,String> upMap = getCmdMap(resultMap.get("ruijieApGeneralApUpRate"),device);
        Map<String,String> downMap = getCmdMap(resultMap.get("ruijieApGeneralApDownRate"),device);
        Map<String,String> groupMap = getCmdMap(resultMap.get("ApGeneralGroup"),device);
        for(String oid:oidList){
            AccessPoints accessPoints = new AccessPoints();
            accessPoints.setDeviceId(id);
            accessPoints.setName(ObjectUtils.isNotEmpty(nameMap)&&ObjectUtils.isNotEmpty(nameMap.get(oid))?nameMap.get(oid):null);
            accessPoints.setMacAddr(ObjectUtils.isNotEmpty(macMap)&&ObjectUtils.isNotEmpty(macMap.get(oid))?macMap.get(oid).replace(" ",":"):null);
            accessPoints.setHostname(ObjectUtils.isNotEmpty(ipMap)&&ObjectUtils.isNotEmpty(ipMap.get(oid))?ipMap.get(oid):null);
            accessPoints.setStatus(ObjectUtils.isNotEmpty(statusMap)&&ObjectUtils.isNotEmpty(statusMap.get(oid))?Integer.valueOf(statusMap.get(oid)):null);
            accessPoints.setNumasoclients(ObjectUtils.isNotEmpty(apStaMap)&&ObjectUtils.isNotEmpty(apStaMap.get(oid))?Integer.valueOf(apStaMap.get(oid)):null);
            accessPoints.setUp(ObjectUtils.isNotEmpty(upMap)&&ObjectUtils.isNotEmpty(upMap.get(oid))?Integer.valueOf(upMap.get(oid)):null);
            accessPoints.setDown(ObjectUtils.isNotEmpty(downMap)&&ObjectUtils.isNotEmpty(downMap.get(oid))?Integer.valueOf(downMap.get(oid)):null);
            accessPoints.setApType(ObjectUtils.isNotEmpty(apTypeMap)&&ObjectUtils.isNotEmpty(apTypeMap.get(oid))?apTypeMap.get(oid):null);
            accessPoints.setType(ObjectUtils.isNotEmpty(hzMap)&&ObjectUtils.isNotEmpty(hzMap.get(oid))?("1".equals(hzMap.get(oid))?"dot11b":"dot11a"):null);
            accessPoints.setApGroup(ObjectUtils.isNotEmpty(groupMap)&&ObjectUtils.isNotEmpty(groupMap.get(oid))?groupMap.get(oid):null);
            list.add(accessPoints);
        }
        accessPointsService.remove(new QueryWrapper<AccessPoints>().lambda()
                .eq(AccessPoints::getDeviceId,id));
        accessPointsService.saveBatch(list);
    }

    @Override
    public void addACAP(Integer id) {
        List<Wirelessoids> wlist = wirelessoidsService.list(new QueryWrapper<Wirelessoids>().lambda()
                .eq(Wirelessoids::getDeviceId,id));
        Map<String, String> resultMap = new HashMap<>();
        if (wlist != null) {
            for (Wirelessoids wirelessoids : wlist) {
                if (wirelessoids.getField() != null && wirelessoids.getOid() != null) {
                    // 将 field 作为键，oid 作为值存入 Map
                    resultMap.put(wirelessoids.getField(), wirelessoids.getOid());
                }
//                else {
//                    throw new ServiceException("部分Oid为空，请保存或检查！");
//                }
            }
        }
        //加ac
        Device device = deviceService.getById(id);
//        if(!"ruijie".equals(device.getOs())){
//            throw new ServiceException("目前设备为"+device.getOs()+",只支持锐捷设备");
//        }
        WirelessSensorsManual wirelessSensors = new WirelessSensorsManual();
        wirelessSensors.setSensorClass("ap-count");
        wirelessSensors.setDeviceId(id);
        wirelessSensors.setSensorType("ciscowlc");
        wirelessSensors.setSensorIndex("0");
        wirelessSensors.setSensorDescr("Connected APs");
        wirelessSensors.setSensorDivisor(1);
        wirelessSensors.setSensorMultiplier(1);
        wirelessSensors.setSensorAggregator("sum");
        String sensorCurrent = getCmdString(resultMap.get("ruijieCurrentUserNum"),device);
        wirelessSensors.setSensorCurrent(ObjectUtils.isNotEmpty(sensorCurrent)?Integer.valueOf(sensorCurrent):null);
        wirelessSensorsManualService.remove(new QueryWrapper<WirelessSensorsManual>().lambda()
                .eq(WirelessSensorsManual::getDeviceId,id)
                .eq(WirelessSensorsManual::getSensorClass,"ap-count"));
        wirelessSensorsManualService.save(wirelessSensors);

        //加ap,所有的都用map来
        List<AccessPoints> list = new ArrayList<>();
        Map<String,String> nameMap = getCmdMap(resultMap.get("ruijieApGeneralApName"),device);
        Map<String,String> ipMap = getCmdMap(resultMap.get("ruijieApGeneralIp"),device);
        List<String> oidList = ipMap.keySet().stream().collect(Collectors.toList());
        Map<String,String> macMap = getCmdMap(resultMap.get("ruijieApGeneralMacAddrColon"),device);
        Map<String,String> statusMap = getCmdMap(resultMap.get("ruijieApGeneralState"),device);
        Map<String,String> apStaMap = getCmdMap(resultMap.get("ruijieApGeneralApStaNum"),device);
        //查看是2.4（1）还是5（2）todo 前端要处理
        Map<String,String> hzMap = getCmdMap(resultMap.get("ruijieApRadioType"),device);
        Map<String,String> apTypeMap = getCmdMap(resultMap.get("ruijieApPID"),device);
        Map<String,String> upMap = getCmdMap(resultMap.get("ruijieApGeneralApUpRate"),device);
        Map<String,String> downMap = getCmdMap(resultMap.get("ruijieApGeneralApDownRate"),device);

        for(String oid:oidList){
            AccessPoints accessPoints = new AccessPoints();
            accessPoints.setDeviceId(id);
            accessPoints.setName(ObjectUtils.isNotEmpty(nameMap)&&ObjectUtils.isNotEmpty(nameMap.get(oid))?nameMap.get(oid):null);
            accessPoints.setMacAddr(ObjectUtils.isNotEmpty(macMap)&&ObjectUtils.isNotEmpty(macMap.get(oid))?macMap.get(oid).replace(" ",":"):null);
            accessPoints.setHostname(ObjectUtils.isNotEmpty(ipMap)&&ObjectUtils.isNotEmpty(ipMap.get(oid))?ipMap.get(oid):null);
            accessPoints.setStatus(ObjectUtils.isNotEmpty(statusMap)&&ObjectUtils.isNotEmpty(statusMap.get(oid))?Integer.valueOf(statusMap.get(oid)):null);
            accessPoints.setNumasoclients(ObjectUtils.isNotEmpty(apStaMap)&&ObjectUtils.isNotEmpty(apStaMap.get(oid))?Integer.valueOf(apStaMap.get(oid)):null);
            accessPoints.setUp(ObjectUtils.isNotEmpty(upMap)&&ObjectUtils.isNotEmpty(upMap.get(oid))?Integer.valueOf(upMap.get(oid)):null);
            accessPoints.setDown(ObjectUtils.isNotEmpty(downMap)&&ObjectUtils.isNotEmpty(downMap.get(oid))?Integer.valueOf(downMap.get(oid)):null);
            accessPoints.setApType(ObjectUtils.isNotEmpty(apTypeMap)&&ObjectUtils.isNotEmpty(apTypeMap.get(oid))?apTypeMap.get(oid):null);
            accessPoints.setType(ObjectUtils.isNotEmpty(hzMap)&&ObjectUtils.isNotEmpty(hzMap.get(oid))?("1".equals(hzMap.get(oid))?"dot11b":"dot11a"):null);
            list.add(accessPoints);
            System.out.println(accessPoints);
        }
        accessPointsService.remove(new QueryWrapper<AccessPoints>().lambda()
                .eq(AccessPoints::getDeviceId,id));
        accessPointsService.saveBatch(list);
    }

    //这个方法主要是用于OID不全的情况
    @Override
    public void addACAPMap(Integer id) {
        List<Wirelessoids> wlist = wirelessoidsService.list(new QueryWrapper<Wirelessoids>().lambda()
                .eq(Wirelessoids::getDeviceId,id));
        Map<String, String> resultMap = new HashMap<>();
        if (wlist != null) {
            for (Wirelessoids wirelessoids : wlist) {
                if (wirelessoids.getField() != null && wirelessoids.getOid() != null) {
                    // 将 field 作为键，oid 作为值存入 Map
                    resultMap.put(wirelessoids.getField(), wirelessoids.getOid());
                }
            }
        }
        //加ac
        Device device = deviceService.getById(id);
//        if(!"ruijie".equals(device.getOs())){
//            throw new ServiceException("目前设备为"+device.getOs()+",只支持锐捷设备");
//        }
        WirelessSensorsManual wirelessSensors = new WirelessSensorsManual();
        wirelessSensors.setSensorClass("ap-count");
        wirelessSensors.setDeviceId(id);
        wirelessSensors.setSensorType("ciscowlc");
        wirelessSensors.setSensorIndex("0");
        wirelessSensors.setSensorDescr("Connected APs");
        wirelessSensors.setSensorDivisor(1);
        wirelessSensors.setSensorMultiplier(1);
        wirelessSensors.setSensorAggregator("sum");
        String sensorCurrent = getCmdString(resultMap.get("ruijieCurrentUserNum"),device);
        wirelessSensors.setSensorCurrent(ObjectUtils.isNotEmpty(sensorCurrent)?Double.valueOf(sensorCurrent):null);
        wirelessSensorsManualService.remove(new QueryWrapper<WirelessSensorsManual>().lambda()
                .eq(WirelessSensorsManual::getDeviceId,id)
                .eq(WirelessSensorsManual::getSensorClass,"ap-count"));
        wirelessSensorsManualService.save(wirelessSensors);

        //加ap
        List<AccessPoints> list = new ArrayList<>();
        LinkedHashMap<String,String> nameMap = getCmdMap(resultMap.get("ruijieApGeneralApName"),device);
        if(ObjectUtils.isEmpty(nameMap)){
            return;
        }
        Map<String,String> ipMap = getCmdMap(resultMap.get("ruijieApGeneralIp"),device);
        Map<String,String> macMap = getCmdMap(resultMap.get("ruijieApGeneralMacAddrColon"),device);
        Map<String,String> statusMap = getCmdMap(resultMap.get("ruijieApGeneralState"),device);
        Map<String,String> apStaMap = getCmdMap(resultMap.get("ruijieApGeneralApStaNum"),device);
        //查看是2.4（1）还是5（2）
        Map<String,String> hzMap = getCmdMap(resultMap.get("ruijieApRadioType"),device);
        Map<String,String> apTypeMap = getCmdMap(resultMap.get("ruijieApPID"),device);
        Map<String,String> upMap = getCmdMap(resultMap.get("ruijieApGeneralApUpRate"),device);
        Map<String,String> downMap = getCmdMap(resultMap.get("ruijieApGeneralApDownRate"),device);

        for (String key : ipMap.keySet()) {
            AccessPoints accessPoints = new AccessPoints();
            accessPoints.setDeviceId(id);
            accessPoints.setName(ObjectUtils.isNotEmpty(nameMap)&&ObjectUtils.isNotEmpty(nameMap.get(key))?nameMap.get(key):null);
            accessPoints.setMacAddr(ObjectUtils.isNotEmpty(macMap)&&ObjectUtils.isNotEmpty(macMap.get(key))?macMap.get(key).replace(" ",":"):null);
            accessPoints.setHostname(ObjectUtils.isNotEmpty(ipMap)&&ObjectUtils.isNotEmpty(ipMap.get(key))?ipMap.get(key):null);
            accessPoints.setStatus(ObjectUtils.isNotEmpty(statusMap)&&ObjectUtils.isNotEmpty(statusMap.get(key))?Integer.valueOf(statusMap.get(key)):null);
            accessPoints.setNumasoclients(ObjectUtils.isNotEmpty(apStaMap)&&ObjectUtils.isNotEmpty(apStaMap.get(key))?Integer.valueOf(apStaMap.get(key)):null);
            accessPoints.setUp(ObjectUtils.isNotEmpty(upMap)&&ObjectUtils.isNotEmpty(upMap.get(key))?Integer.valueOf(upMap.get(key)):null);
            accessPoints.setDown(ObjectUtils.isNotEmpty(downMap)&&ObjectUtils.isNotEmpty(downMap.get(key))?Integer.valueOf(downMap.get(key)):null);
            accessPoints.setType(ObjectUtils.isNotEmpty(hzMap)&&ObjectUtils.isNotEmpty(hzMap.get(key))?
                    ("1".equals(hzMap.get(key))?"dot11b":"dot11a"):null);
            accessPoints.setApType(ObjectUtils.isNotEmpty(apTypeMap)&&ObjectUtils.isNotEmpty(apTypeMap.get(key))?apTypeMap.get(key):null);
            list.add(accessPoints);
        }
        accessPointsService.remove(new QueryWrapper<AccessPoints>().lambda()
                .eq(AccessPoints::getDeviceId,id));
        accessPointsService.saveBatch(list);
    }

    @Override
    public void completionACAP(Integer deviceId) {
        List<Wirelessoids> wlist = wirelessoidsService.list(new QueryWrapper<Wirelessoids>().lambda()
                .eq(Wirelessoids::getDeviceId,deviceId));
        Map<String, String> resultMap = new HashMap<>();
        if (wlist != null) {
            for (Wirelessoids wirelessoids : wlist) {
                if (wirelessoids.getField() != null && wirelessoids.getOid() != null) {
                    // 将 field 作为键，oid 作为值存入 Map
                    resultMap.put(wirelessoids.getField(), wirelessoids.getOid());
                }
            }
        }
        Device device = deviceService.getById(deviceId);
        //获取所有的ap
        List<AccessPoints> list = accessPointsService.list(new QueryWrapper<AccessPoints>().lambda()
                .eq(AccessPoints::getDeviceId,deviceId));

        Map<String,AccessPoints> apMap = new HashMap<>();
        System.out.println("+++++++++++++++++++++++++++++++++");
        System.out.println("+++++++++++++++++++++++++++++++++");
        Map<String,String> nameMap = getCmdMap(resultMap.get("ruijieApGeneralApName"),device);
        Map<String,String> ipMap = getCmdMap(resultMap.get("ruijieApGeneralIp"),device);
        List<String> oidList = nameMap.keySet().stream().collect(Collectors.toList());
        Map<String,String> macMap = getCmdMap(resultMap.get("ruijieApGeneralMacAddrColon"),device);
        Map<String,String> statusMap = getCmdMap(resultMap.get("ruijieApGeneralState"),device);
        Map<String,String> apStaMap = getCmdMap(resultMap.get("ruijieApGeneralApStaNum"),device);
        //查看是2.4（1）还是5（2）todo 前端要处理
        Map<String,String> hzMap = getCmdMapHZ(resultMap.get("ruijieApRadioType"),device);
        Map<String,String> apTypeMap = getCmdMap(resultMap.get("ruijieApPID"),device);
        Map<String,String> upMap = getCmdMap(resultMap.get("ruijieApGeneralApUpRate"),device);
        Map<String,String> downMap = getCmdMap(resultMap.get("ruijieApGeneralApDownRate"),device);
        System.out.println(nameMap);
        System.out.println(ipMap);
        System.out.println(oidList);
        for(String oid:oidList){
            AccessPoints accessPoints = new AccessPoints();
            accessPoints.setMacAddr(ObjectUtils.isNotEmpty(macMap)&&ObjectUtils.isNotEmpty(macMap.get(oid))?macMap.get(oid).replace(" ",":"):null);
            accessPoints.setHostname(ObjectUtils.isNotEmpty(ipMap)&&ObjectUtils.isNotEmpty(ipMap.get(oid))?ipMap.get(oid):null);
            accessPoints.setStatus(ObjectUtils.isNotEmpty(statusMap)&&ObjectUtils.isNotEmpty(statusMap.get(oid))?Integer.valueOf(statusMap.get(oid)):null);
            accessPoints.setNumasoclients(ObjectUtils.isNotEmpty(apStaMap)&&ObjectUtils.isNotEmpty(apStaMap.get(oid))?Integer.valueOf(apStaMap.get(oid)):null);
            accessPoints.setUp(ObjectUtils.isNotEmpty(upMap)&&ObjectUtils.isNotEmpty(upMap.get(oid))?Integer.valueOf(upMap.get(oid)):null);
            accessPoints.setDown(ObjectUtils.isNotEmpty(downMap)&&ObjectUtils.isNotEmpty(downMap.get(oid))?Integer.valueOf(downMap.get(oid)):null);
            accessPoints.setApType(ObjectUtils.isNotEmpty(apTypeMap)&&ObjectUtils.isNotEmpty(apTypeMap.get(oid))?apTypeMap.get(oid):null);
            accessPoints.setType(ObjectUtils.isNotEmpty(hzMap)&&ObjectUtils.isNotEmpty(hzMap.get(oid))?("1".equals(hzMap.get(oid))?"dot11b":"dot11a"):null);
            apMap.put(ObjectUtils.isNotEmpty(nameMap)&&ObjectUtils.isNotEmpty(nameMap.get(oid))?nameMap.get(oid):null,accessPoints);
        }
        for(AccessPoints accessPoints:list){
            AccessPoints ap = apMap.get(accessPoints.getName());
            if(ObjectUtils.isEmpty(ap)){
                continue;
            }
            accessPoints.setMacAddr(ObjectUtils.isNotEmpty(ap.getMacAddr())?ap.getMacAddr():accessPoints.getMacAddr());
            accessPoints.setHostname(ObjectUtils.isEmpty(ap.getHostname())?accessPoints.getHostname():ap.getHostname());
            accessPoints.setStatus(ObjectUtils.isEmpty(ap.getStatus())?accessPoints.getStatus():ap.getStatus());
            accessPoints.setNumasoclients(ObjectUtils.isEmpty(ap.getNumasoclients())?accessPoints.getNumasoclients():ap.getNumasoclients());
            accessPoints.setUp(ObjectUtils.isEmpty(ap.getUp())?accessPoints.getUp():ap.getUp());
            accessPoints.setDown(ObjectUtils.isEmpty(ap.getDown())?accessPoints.getDown():ap.getDown());
            accessPoints.setApType(ObjectUtils.isEmpty(ap.getApType())?accessPoints.getApType():ap.getApType());
            accessPoints.setType(ObjectUtils.isEmpty(ap.getType())?accessPoints.getType():ap.getType());
        }
        accessPointsService.updateBatchById(list) ;
    }

    private String getCmdString(String oid,Device device){
        if(ObjectUtils.isEmpty(oid))return null;
        String result = "";
        try {
            // 构建命令数组（避免空格分割问题）
            String[] cmd = {"snmpwalk", "-"+device.getSnmpver(), "-c", device.getCommunity(), device.getHostname(), oid};
            // 创建进程
            Process process = Runtime.getRuntime().exec(cmd);
            // 读取标准输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println("++++++++++++++++++++");
                System.out.println(line);
                // 找到第一个 ": " 的位置
                int index = line.indexOf(": ");
                if (index != -1) {
                    // 从 ": " 之后截取字符串
//                    result = line.trim().replaceFirst("^(STRING:|INTEGER:|IpAddress:|Counter32:) ", "").replace("\"", "").trim();
                    result = line.substring(index + 2).trim();
                }
            }
            // 读取错误输出
            BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            while ((line = errorReader.readLine()) != null) {
                System.out.println("=====================");
                System.err.println(line);
                return null;
            }
        // 等待进程结束并获取退出码
            int exitCode = process.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    private List<String> getCmdList(String oid, Device device){
        if(ObjectUtils.isEmpty(oid))return null;
        List<String> list = new ArrayList<>();
        try {
            // 构建命令数组（避免空格分割问题）
            String[] cmd = {"snmpwalk", "-v2c", "-c", device.getCommunity(), device.getHostname(), oid};
            // 创建进程
            Process process = Runtime.getRuntime().exec(cmd);
            // 读取标准输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            int index;
            while ((line = reader.readLine()) != null) {
                System.out.println("++++++++++++++++++++");
                System.out.println(line);
                // 找到第一个 ": " 的位置
                index = line.indexOf(": ");
                if (index != -1) {
                    // 从 ": " 之后截取字符串
                    line = line.substring(index + 2).trim();
                    list.add(line);
//                    line = line.trim().replaceFirst("^(STRING:|INTEGER:|IpAddress:|Counter32:) ", "").replace("\"", "").trim();
                }
            }
            // 读取错误输出
            BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            while ((line = errorReader.readLine()) != null) {
                System.out.println("=====================");
                System.err.println(line);
                return null;
            }
            // 等待进程结束并获取退出码
            int exitCode = process.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    private LinkedHashMap<String, String> getCmdMap(String oid, Device device){
        if(ObjectUtils.isEmpty(oid))return null;
        LinkedHashMap<String, String> map = new LinkedHashMap<>();
        try {
            // 构建命令数组（避免空格分割问题）
            String[] cmd = {"snmpwalk", "-v2c", "-c", device.getCommunity(), device.getHostname(), oid};
            // 创建进程
            Process process = Runtime.getRuntime().exec(cmd);
            // 读取标准输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            int dotCount = 0;
            int splitIndex = 0;
            while ((line = reader.readLine()) != null) {
                System.out.println("============");
                System.out.println(line);
                String[] parts = line.split("=");
                if(splitIndex == 0){
                    for (int i = parts[0].length() - 1; i >= 0; i--) {
                        if (parts[0].charAt(i) == '.') {
                            dotCount++;
                            if (dotCount == 6) {
                                splitIndex = i + 1;
                                break;
                            }
                        }
                    }
                }
                if (parts.length == 2) {
                    String keyPart = parts[0].trim();
                    // 去除可能的 STRING: 或 INTEGER: 前缀，并去掉双引号
                    String valuePart = parts[1].substring(parts[1].indexOf(": ") + 2).replace("\"", "").trim();
                    String result = keyPart.substring(splitIndex);
                    map.put(result, valuePart);
                }
            }
            // 读取错误输出
            BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            while ((line = errorReader.readLine()) != null) {
                System.out.println("=====================");
                System.err.println(line);
//                return null;
            }
            // 等待进程结束并获取退出码
            int exitCode = process.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    private LinkedHashMap<String, String> getCmdMapHZ(String oid, Device device){
        if(ObjectUtils.isEmpty(oid))return null;
        LinkedHashMap<String, String> map = new LinkedHashMap<>();
        try {
            // 构建命令数组（避免空格分割问题）
            String[] cmd = {"snmpwalk", "-v2c", "-c", device.getCommunity(), device.getHostname(), oid};
            // 创建进程
            Process process = Runtime.getRuntime().exec(cmd);
            // 读取标准输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            int dotCount = 0;
            int splitIndex = 0;
            while ((line = reader.readLine()) != null) {
                String[] parts = line.split("=");
                if(splitIndex == 0){
                    for (int i = parts[0].length() - 1; i >= 0; i--) {
                        if (parts[0].charAt(i) == '.') {
                            dotCount++;
                            if (dotCount == 6) {
                                splitIndex = i + 1;
                                break;
                            }
                        }
                    }
                }
                if (parts.length == 2) {
                    String keyPart = parts[0].trim();
                    // 去除可能的 STRING: 或 INTEGER: 前缀，并去掉双引号
                    String valuePart = parts[1].substring(parts[1].indexOf(": ") + 2).replace("\"", "").trim();
                    String result = keyPart.substring(splitIndex,keyPart.length() - 2);
                    // 如果map中已有key，则将value与valuePart相加
                    if (map.containsKey(valuePart)) {
                        map.put(valuePart, "2.4HZ/5HZ");
                    } else {
                        map.put(valuePart, result=="1"?"2.4HZ":"5HZ");
                    }
                }
            }
            // 读取错误输出
            BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            while ((line = errorReader.readLine()) != null) {
                System.out.println("=====================");
                System.err.println(line);
                return null;
            }
            // 等待进程结束并获取退出码
            int exitCode = process.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    public static void main(String[] args) {
        String line = "iso.3.6.1.4.1.14179.2.2.1.1.3.248.183.226.211.46.96 = STRING: \"RD-BG-03-03\"";
        String[] parts = line.split("=");
        int dotCount = 0;
        int splitIndex = 0;
        if(splitIndex == 0){
            for (int i = parts[0].length() - 1; i >= 0; i--) {
                if (parts[0].charAt(i) == '.') {
                    dotCount++;
                    if (dotCount == 6) {
                        splitIndex = i + 1;
                        break;
                    }
                }
            }
        }
        if (parts.length == 2) {
            String keyPart = parts[0].trim();
            // 去除可能的 STRING: 或 INTEGER: 前缀，并去掉双引号
            String valuePart = parts[1].substring(parts[1].indexOf(": ") + 2).replace("\"", "").trim();
            String result = keyPart.substring(splitIndex);
            System.out.println( result);
            System.out.println(valuePart);
        }
    }
}
